from flask import request
from functools import wraps

from app.utils.exception import ValidationError


def blank_not_allowed(value):
    # Add your custom validation logic here
    if value == '':
        return "The field cannot be empty"
    return None


def validate(validation_rules):
    """
    Decorator for validation
    """
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            data = request.json
            errors = []
            for rule in validation_rules:
                if isinstance(rule["field"], list):
                    for field_name in rule["field"]:
                        validator = rule["validator"]
                        error_message = validator(data.get(field_name))
                        if error_message:
                            errors.append({
                                field_name: error_message
                            })
                else:
                    field_name = rule["field"]
                    validator = rule["validator"]
                    error_message = validator(data.get(field_name))
                    if error_message:
                        errors.append({
                            field_name: error_message
                        })
            if errors:
                return ValidationError(errors=errors)
            return f(*args, **kwargs)
        return wrapper
    return decorator
